const fs = require('fs');

var orders = [];


function readOrder(target) {

    fs.readFile('./order.json', 'utf-8', (err, data) => {
        target = JSON.parse(data);
        console.log(target);
    });
}

//增加
//k 是 key  v 是 value
function addOrder(k, v) {
    //矫正
    fs.readFile('./order.json', 'utf-8', (err, data) => {
        orders = JSON.parse(data); //解析数据
        console.log('添加数据之前：');
        console.log(orders);
        var o = {
            gid: k,
            goodName: v.goodName,
            gPrice: v.gPrice
        }
        orders.push(o);
        fs.writeFile('./order.json', JSON.stringify(orders), err => {
            if (err) {
                throw err;
                return false;
            }
            console.log('添加数据成功！');
        });
    });

    /*这种方法是错误的不可采取传统的方，会造成数据错误添加
    fs.open('./order.json', 'a+', (err, fd) => {
        if (err) {
            throw err;
            return false;
        }
        var o = {
            gid: k,
            goodName: v.goodName,
            gPrice: v.gPrice
        }
        fs.write(fd, JSON.stringify(o), (err, bytes, str) => {
            if(err){
                fs.close(fd);
                throw err;
            return false;
            }
            console.log('添加数据成功！共写入'+bytes+'字节。');
        });
    });
    */
}
//readOrder(orders);错误方法的语句

/*
addOrder('003', {
    goodName: '矿泉水',
    gPrice: 2
})
*/



//修改
function modifOrder(k, v) {

    fs.readFile('./order.json', 'utf-8', (err, data) => {
        orders = JSON.parse(data); //解析数据
        console.log('修改数据之前：');
        console.log(orders);

        //读取
        for (var d of orders) {
            if (d.gid == k) {
                d.goodName = v.goodName;
                d.gPrice = v.gPrice;
                break;
            }
        }

        //重写
        fs.writeFile('./order.json', JSON.stringify(orders), err => {
            if (err) {
                throw err;
                return false;
            }
            console.log('修改数据成功！');
        });
    });
}
/*
modifOrder('003', {
    goodName: '比亚迪',
    gPrice: 268734
});
*/



//删除
function delOrder(k) {
    fs.readFile('./order.json', 'utf-8', (err, data) => {
        orders = JSON.parse(data); //解析数据
        console.log('删除数据之前：');
        console.log(orders);

        //遍历方法之外删除
        var pos = -1;
        for (var i = 0; i < orders.length; i++) {
            if (orders[i].gid == k) {
                pos = i;
                break;
            }
        }
        orders.splice(pos,1);

        fs.writeFile('./order.json', JSON.stringify(orders), err => {
            if (err) {
                throw err;
                return false;
            }
            console.log('删除数据成功！');
        });
    });
}
delOrder('003');





